const auth = require('basic-auth');
const basicAuth = require('basic-auth')
const jwt = require('jsonwebtoken')

class Auth {
  constructor(level) {
    this.level = level || 1
    Auth.USER = 8  // Auth.USER 是静态变量，this.USER 属于私有
    Auth.ADMIN = 16
    Auth.SUPER_ADMIN = 32
  }
  get m() {
    return async (ctx, next) => {
      // token校验
      //token传递过来
      // token body header
      // httpbaseauto身份认证机制
      const userToken = basicAuth(ctx.req)
      console.log(userToken)

      let errMsg = 'token不合法'
      // ctx.body = token;
      if(!userToken || !userToken.name) {
        throw new global.errs.Forbidden()
      }
      let decode = null;
      try {
        decode = jwt.verify(userToken.name, global.config.security.secretKey)
      } catch (error) {
        if(error.name == 'TokenExpiredError') {
          errMsg = 'token已过期'
        }
        throw new global.errs.Forbidden(errMsg)
      }
      if(decode) {
        if(decode.scope < this.level) {
          errMsg = '权限不足'
          throw new global.errs.Forbidden()
        }
      }
      
      // 如果中间没有出现问题可以
      ctx.auth = {
        uid:decode.uid,
        scope: decode.scope
      }
      await next()
    }
  }

  // 验证token是否有效
  static verifyToken(token) {
    try {
        jwt.verify(token, global.config.security.secretKey)

        return true;
    } catch (e) {
        return false
    }
  }

}

module.exports = {
  Auth
}